﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SugarWebApi.Json
{
	public class JsonSerializer
	{

		public static void Serialize(
			Stream output,
			object target)
		{
			using (TextWriter writer = new StreamWriter(output))
			{
				Serialize(writer, target);
			}
		}

		public static void Serialize(
			TextWriter writer,
			object target)
		{
			Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
			serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
			serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

			StringBuilder buffer = new StringBuilder();
			using (StringWriter swriter = new StringWriter(buffer))
			{
				serializer.Serialize(swriter, target);
			}
			Trace.Debug("Posted Object");
			Trace.Debug(buffer.ToString());
			writer.Write(buffer.ToString());

			//using (Newtonsoft.Json.JsonWriter jwriter = new Newtonsoft.Json.JsonTextWriter(writer))
			//{
			//  serializer.Serialize(jwriter, target);
			//}
		}

		public static TResult Deserialize<TResult>(
			Stream input) where TResult : class
		{
			return Deserialize(input, typeof(TResult)) as TResult;
		}

		public static object Deserialize(
			Stream input)
		{
			return Deserialize(input, null);
		}

		public static object Deserialize(
			Stream input,
			Type objectType)
		{
			using (StreamReader reader = new StreamReader(input))
			{
				return Deserialize(reader, objectType);
			}
		}

		public static object Deserialize(
			TextReader reader,
			Type objectType)
		{
			Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
			serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
			serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

			string buffer = reader.ReadToEnd();
			Trace.Debug(buffer);
			/*
			using (Newtonsoft.Json.JsonReader jreader = new Newtonsoft.Json.JsonTextReader(reader))
			{
			*/
			using (Newtonsoft.Json.JsonReader jreader = new Newtonsoft.Json.JsonTextReader(new StringReader(buffer)))
			{
				if (objectType != null) return serializer.Deserialize(jreader, objectType);
				else return  serializer.Deserialize(jreader);
			}
		}
	}
}
